const express = require("express");
// const { model } = require('mongoose')
const router = express.Router();
const studentDB = require("../../schemas/student");
const path = require("path");

// 获取学员列表
router.get("/studentList", async (req, res) => {
  // 前端要 具体页数currentPage 具体的数据条数pageSize  筛选项:kindName(类别) courseName(课程) className(班期)
  const { kindName, courseName, className, currentPage, pageSize } = req.query;
  let data = await studentDB.find();

  // 筛选类别
  if (kindName) {
    data = data.filter((item) => {
      return item.kindName === kindName;
    });
  }
  // 筛选课程名
  if (courseName) {
    data = data.filter((item) => {
      return item.courseName === courseName;
    });
  }
  // 筛选班期
  if (className) {
    data = data.filter((item) => {
      return item.className === className;
    });
  }

  // 按照更新事件倒序排列
  data.sort((a, b) => {
    return b.updateTime - a.updateTime;
  });

  // 总数
  const total = data.length;

  // 返回splice切下来的数组  currentPage2  pageSize5
  data = data.splice(pageSize * (currentPage - 1), pageSize);

  res.send({
    code: 0,
    data,
    total,
  });
});

// 获取课程分类对象
router.get("/courseObj", (req, res) => {
  res.sendFile(path.join(__dirname, "../../dataJson/courseObj.json"));
});

// 修改学员信息
router.post("/reviseStudent", async (req, res) => {
  const student = req.body;
  console.log(student)
  if (Array.isArray(student.location)) {
    student.location = student.location.join("/");
  }
  await studentDB.updateOne(
    { phoneNumber: student.phoneNumber },
    { info: student }
  );
  res.send({
    code: 0,
    txt: "修改成功了",
  });
});

// 修改学员班期
router.post("/reviseStudentClass", async (req, res) => {
  const { className, phoneNumber } = req.body;
  await studentDB.updateOne({ phoneNumber }, { className });
  res.send({
    code: 0,
    txt: "修改成功",
  });
});

// 修改课程是否启用
// reviseIsEnable
router.post("/reviseIsEnable", async (req, res) => {
  const { phoneNumber, isEnable } = req.body;

  // console.log(phoneNumber, isEnable)
  await studentDB.updateOne({ phoneNumber }, { isEnable: !isEnable });
  let txt = "";
  if (isEnable) {
    txt = "关闭成功";
  } else {
    txt = "开启成功";
  }

  res.send({
    code: 0,
    txt,
  });
});

module.exports = router;
